//
//  HJHHttpManager.swift
//  WeiBoPro
//
//  Created by nadyboy on 2018/5/18.
//  Copyright © 2018年 hjh. All rights reserved.
//

enum httpRequestType {
    case GET
    case POST
}

import UIKit
import AFNetworking

class HJHHttpManager: AFHTTPSessionManager {
    var accessToken:String? = "2.006B8inFA6r7zB0dd854741f1nNeJC"
    
    /// 单利
    static let shareInstance = HJHHttpManager()
    
    /// 专门负责拼接token的
    func requstAcceccToken(requsetType:httpRequestType = .GET, urlString:String, paramters:[String:Any]?, successComplte:@escaping ((_ result: Any?, _ isSuccess: Bool)->())) -> (){
        ///0 判断token是否存在
        guard let token = accessToken else {
            //FIXME:过期了要重新登陆
            print("token不存在------")
            successComplte(nil,false)
             return
        }
        ///1 判断参数字典是否存在呢，不存在就要设置
        var paramters = paramters
        if paramters == nil {
            paramters = [String:Any]()
        }
        ///2 设置字典 ，此处字典一定存在
        paramters!["access_token"] = token
        
        httpRequst(urlString: urlString, paramters: paramters!, successComplte: successComplte)
    }
    
    /// 封装网络请求方法
    ///
    /// - Parameters:
    ///   - Method: GET/POST, 默认是GET请求
    ///   - URLString: 请求地址
    ///   - parameters: 参数
    ///   - completed: 结束回调
    func httpRequst(requsetType:httpRequestType = .GET, urlString:String, paramters:[String : Any]?, successComplte:@escaping ((_ result: Any?, _ isSuccess: Bool)->())) -> () {
        
        /// 定义成功回调闭包
        let success = { (task: URLSessionDataTask,json: Any?)->() in
            successComplte(json,true)
        }
        
        /// 定义失败回调闭包
        let failure = {(task: URLSessionDataTask?, error: Error)->() in
            print("请求失败----\(error.localizedDescription)")
            if  (task?.response as? HTTPURLResponse)?.statusCode == 400 {
                print("token过期了额-----")
                //FIXME: 发送通知重新登陆
            }
            successComplte(nil,false)
        }
        ///get请求
        if requsetType == .GET {
           
            get(urlString, parameters: paramters, progress: nil, success: success, failure: failure)
        }
        ///post请求
        else
        {
            post(urlString, parameters: paramters, progress: nil, success: success, failure: failure )
        }
    }
}
